#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/11/12 11:03
# @Author  : huidong.bai
# @File    : test.py
# @Software: PyCharm

import numpy as np
import cv2
from matplotlib import pyplot as plt

# 设置最低特征点匹配数量为5
MIN_MATCH_COUNT = 5

# 图片路径
template_img = './1.png'
target_img = './2.png'


# 基于FLANN的匹配器(FLANN based Matcher)定位图片, precision为识别精度
def findKeyImage(template_img_url, target_img_url, precision):
    # 需要查询的图片
    template = cv2.imread(template_img_url, 0)
    # 关键特征图片
    target = cv2.imread(target_img_url, 0)
    # 创建SIFT检测器
    sift = cv2.SIFT_create()
    # 使用SIFT找到关键点和描述符
    kp1, des1 = sift.detectAndCompute(template, None)
    kp2, des2 = sift.detectAndCompute(target, None)
    # 创建设置FLANN匹配
    FLANN_INDEX_KDTREE = 0
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(des1, des2, k=2)
    # 保存优秀的特征值
    key_point = []
    # 舍弃大于0.5的匹配
    for m, n in matches:
        if m.distance < precision * n.distance:
            key_point.append(m)
    if len(key_point) > MIN_MATCH_COUNT:
        # 获取关键点的坐标
        src_pts = np.float32([kp1[m.queryIdx].pt for m in key_point]).reshape(-1, 1, 2)

        # 获取区域中间绝对坐标
        points_x = []
        points_y = []
        rows, _, _ = src_pts.shape
        for r in range(0, rows):
            points_x.append(src_pts[r][0][0])
            points_y.append(src_pts[r][0][1])
        x = int((points_x[0] + points_x[-1]) / 2)
        y = int((min(points_y) + max(points_y)) / 2)
        print('关键坐标信息为：(%s,%s)' % (x, y))

        dst_pts = np.float32([kp2[m.trainIdx].pt for m in key_point]).reshape(-1, 1, 2)
        # 计算变换矩阵和MASK
        M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
        matchesMask = mask.ravel().tolist()
        h, w = template.shape
        # 使用得到的变换矩阵对原图像的四个角进行变换，获得在目标图像上对应的坐标
        pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)
        dst = cv2.perspectiveTransform(pts, M)
        cv2.polylines(target, [np.int32(dst)], True, 0, 2, cv2.LINE_AA)
    else:
        print("图片中找不到足够的有效信息：%d/%d" % (len(key_point), MIN_MATCH_COUNT))
        matchesMask = None

    draw_params = dict(matchColor=(0, 255, 0), singlePointColor=None, matchesMask=matchesMask, flags=2)
    result = cv2.drawMatches(template, kp1, target, kp2, key_point, None, **draw_params)

    return result


if __name__ == '__main__':
    print_info = findKeyImage(template_img, target_img, 0.3)
    # 绘制结果
    plt.imshow(print_info)
    plt.show()
